// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Sea patrol
// -----------------------------------------------
if (!isServer) exitWith {};

private [
	"_position",
	"_pilot",
	"_gunner",
	"_vehicle",
	"_group",
	"_combatmode",
	"_behaviour",
	"_enemys",
	"_distancemax",
	"_cible",
	"_count"
];

_vehicle  = _this select 0;
_position = _this select 1;

_pilot = driver _vehicle;
_gunner = gunner _vehicle;

_group = group _pilot;

_combatmode = "RED";
_behaviour = "COMBAT";

while {((getDammage _vehicle < 0.6) and (count (units _group) > 0))} do {
	_group setCombatMode _combatmode;
	_group setBehaviour _behaviour;

	_count = 0;
	_distancemax = 1000;
	_enemys = (getPosATL _vehicle) nearEntities ["AllVehicles", 300];
	{
		if (side (driver _x) in wcside) then {
			_pilot reveal (driver _x);
			if (_vehicle distance _x < _distancemax) then {_distancemax = _vehicle distance _x; _cible = _x};
			_count = _count + 1;
		};
		sleep 0.05;
	} foreach _enemys;

	if (_count == 0) then {
		if ([(position _vehicle) select 0, (position _vehicle) select 1] distance _position < 1000) then {
			_position = [wcmaptopright, wcmapbottomleft, "onsea"] call WC_fnc_createposition;
		};
		_pilot doMove _position;
	} else {
		if (!isNull _gunner) then {
			_gunner reveal _cible;
			_gunner doTarget _cible;
			_gunner doFire _cible;
		};
		_pilot doMove (position _cible);
	};
	sleep 60;
};

{
	_x setDamage 1;
} foreach (units _group);

_vehicle setDamage 1;